using System;
using System.IO;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint;

namespace PS.WebParts.Rollup
{
    public class RollUpToolpartProp : ToolPart
    {
        static string _toolpartQualifier = "PSRollupDataFormToolpartProp";
        static string _dataSourcesID = _toolpartQualifier + "DataSources";

        private readonly string psNamespace = "http://schemas.portalsolutions.net/Rollup/DataView/";

        private RollUpDataFormWebPart _owner;
        private string _editDataSourcesButton;
        private string _editButtonSourceViewEventHandler;

        private string replaceNameChangedButton;
        private string replaceNameChangedButtonEventHandler;
        
        private Button replaceNameChangedButtton = new Button();
        private HyperLink linkToDataSource = new HyperLink();

        public RollUpToolpartProp (RollUpDataFormWebPart owner)
        {
            this._owner = owner;
            var serverURL = SPContext.Current.Site.ServerRelativeUrl;
            if (!serverURL.EndsWith("/")) serverURL += "/";
            _editButtonSourceViewEventHandler = "javascript:" +
                "MsoContentToolpartBasic" +
                "Edit('" +
                SPHttpUtility.EcmaScriptStringLiteralEncode(SPHttpUtility.UrlPathEncode(serverURL + "_layouts/zoombldr.aspx", true)) + 
                "',{0})";

            replaceNameChangedButtonEventHandler = "OnReplaceClick";
                       
            replaceNameChangedButtton.CssClass = "UserButton";
            replaceNameChangedButtton.ID = "bbb";
            replaceNameChangedButtton.Text = "Replace NameChanged";
        }

        protected void replaceNameChangedButtton_Command(object sender, CommandEventArgs e)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        private string ReplaseGroupFunction(string xsl)
        {
            XmlDocument xDoc = new XmlDocument();
            xDoc.LoadXml(xsl);
            XmlNamespaceManager xnm = new XmlNamespaceManager(xDoc.NameTable);
            xnm.AddNamespace("xsl", "http://www.w3.org/1999/XSL/Transform");
            XmlNode root = xDoc.SelectSingleNode("/Xsl");
            XmlNode node = xDoc.SelectSingleNode("//xsl:stylesheet", xnm);
            XmlAttribute attr = xDoc.CreateAttribute("xmlns:ps");
            attr.Value = psNamespace;
            node.Attributes.Append(attr);
            using (StringWriter sw = new StringWriter(new StringBuilder()))
            {
                xDoc.Save(sw);
                string res = sw.ToString();
                res = res.Replace("ddwrt:NameChanged(", "ps:NameChanged(");
                return res;
            }
        }

        public void OnReplaceClick(object sender, EventArgs e)
        {
            _owner.Xsl = ReplaseGroupFunction(_owner.Xsl);
        }

        protected override void CreateChildControls()
        {
            //bool flag1 = Utility.CheckForCustomToolpane(this.Page);
            ScriptLink.Register(this.Page, "ctp.js", true);

            _editDataSourcesButton = CreateEditButton("DataSource Editor...",
                _editButtonSourceViewEventHandler, "a", _dataSourcesID);

            /*replaceNameChangedButton = "<input id=\"" + _toolpartQualifier + "b" +
                                       "\" type=\"button\" class=\"UserButton\" style=\"width:"
                                       + SPHttpUtility.EcmaScriptStringLiteralEncode("150") + "px;\" value=\""
                                       + SPHttpUtility.HtmlEncode("Replace NameChanged...") + "\" onclick=\"" +
                                       SPHttpUtility.NoEncode(replaceNameChangedButtonEventHandler) + "\" />";*/

            replaceNameChangedButton = CreateEditButton("Replace NameChanged...", replaceNameChangedButtonEventHandler,
                                                        "b", "");
            Controls.Add(replaceNameChangedButtton);

            #region Add DataSource link
            //MJM
            string siteCollectionUrl = SPContext.Current.Web.Url;// SPContext.Current.Site.Url.TrimEnd('/');
            string pageUrl = this.Page.Request.RawUrl;
            string webPartTitle = _owner.Title;
            string linkText = "XML Data Source Link";
            
            linkToDataSource.NavigateUrl = string.Format("{0}/_layouts/ps/rollup/rollupds.ashx?pageurl={1}&webparttitle={2}", siteCollectionUrl, pageUrl, webPartTitle);

            linkToDataSource.Text = linkText;
            linkToDataSource.ToolTip = linkText;

            Controls.Add(linkToDataSource);
            #endregion

            base.CreateChildControls();
        }


        private static string CreateEditButton(string buttonText, string editButtonEventHandler, string buttonID, string field)
        {
            return ("<input id=\"" + _toolpartQualifier + buttonID + "\" type=\"button\" class=\"UserButton\" style=\"width:" + SPHttpUtility.EcmaScriptStringLiteralEncode("150") + "px;\" value=\"" 
                + SPHttpUtility.HtmlEncode(buttonText) + "\" onclick=\"" + 
                SPHttpUtility.NoEncode(string.Format(editButtonEventHandler, field, "ltr")) + "\" />");
        }

    

        public override void ApplyChanges()
        {
            this.EnsureChildControls();
            string val = this.Page.Request.Form[_dataSourcesID];
            if (!string.IsNullOrEmpty(val))
            {
                _owner.DataSourcesString = val;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Controls.Add(replaceNameChangedButtton);
            replaceNameChangedButtton.Click += OnReplaceClick;
        }

        protected override void RenderToolPart(HtmlTextWriter output)
        {
            string str = this._owner.DataSourcesString;
            //str = str.Replace(RollUpDataFormWebPart.DataSourcePrefix, "");
            this.Page.ClientScript.RegisterHiddenField(_dataSourcesID,
                                                       SPHttpUtility.NoEncode(str));

            output.AddAttribute(HtmlTextWriterAttribute.Class, "UserGeneric", false);
            output.RenderBeginTag(HtmlTextWriterTag.Div);

            output.AddAttribute(HtmlTextWriterAttribute.Class, "UserSectionHead ms-bold", false);
            output.RenderBeginTag(HtmlTextWriterTag.Div);
            output.WriteLine(
                SPHttpUtility.HtmlEncode("Data Source Editor"));
            output.RenderEndTag();
            output.AddAttribute(HtmlTextWriterAttribute.Class, "UserSectionBody", false);
            output.RenderBeginTag(HtmlTextWriterTag.Div);
            //if (!base._downLevel && !flag1)

            output.WriteLine(
                SPHttpUtility.HtmlEncodeAllowSimpleTextFormatting("To edit Data Sources, click on the button below"));
            output.WriteLine("<br/>");
            output.AddAttribute(HtmlTextWriterAttribute.Class, "UserControlGroup", false);
            output.RenderBeginTag(HtmlTextWriterTag.Div);
            output.WriteLine(SPHttpUtility.NoEncode(_editDataSourcesButton));

            output.WriteLine("<br></br>");
            replaceNameChangedButtton.RenderControl(output);
            output.WriteLine("<br/><br/>");            

            linkToDataSource.RenderControl(output);
            output.WriteLine("<br/><br/>");            

            output.RenderEndTag();
            output.RenderEndTag();
            output.RenderEndTag();
        }
    }

    public class RollUpToolpart : ToolPart
    {
        internal string partName = "RollUp";
        
        public override void ApplyChanges()
        {
        }

        public override void CancelChanges()
        {
        }

        protected override void RenderToolPart(HtmlTextWriter output)
        {
            output.Write("<br><center>"+partName+" for WSS v3<br>v1.0</center><br><br>");

        }
        public override void SyncChanges()
        {
        }

    }
}
